<template>
    <view class="container">
        <view class="header">
            <text class="title">选择自提门店</text>
        </view>
        
        <view class="store-list">
            <view 
                class="store-item" 
                v-for="(item, index) in storeList" 
                :key="index"
                @click="selectStore(item)"
            >
                <view class="store-img" v-if="item.logo">
                    <image :src="item.logo" class="img" mode="aspectFill" />
                </view>
                <view class="store-info">
                    <view class="store-name">{{ item.name }}</view>
                    <view class="store-address">{{ item.areaName }}{{ item.detailAddress }}</view>
                    <view class="store-phone" v-if="item.phone">联系电话：{{ item.phone }}</view>
                </view>
                <view class="store-actions">
                    <view class="action-buttons">
                        <view class="phone-btn" @click.stop="callPhone(item.phone)" v-if="item.phone">
                            <text class="icon-phone">📞</text>
                        </view>
                        <view class="map-btn" @click.stop="showMap(item)">
                            <text class="icon-map">📍</text>
                        </view>
                    </view>
                    <view class="distance-info" v-if="item.distance">
                        <text class="distance-text">距离{{ item.distance.toFixed(2) }}km</text>
                    </view>
                </view>
            </view>
        </view>
        
        <view class="empty" v-if="storeList.length === 0 && !loading">
            <text>暂无自提门店</text>
        </view>
        
        <view class="loading" v-if="loading">
            <text>加载中...</text>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            storeList: [],
            loading: false,
            items: [],
            deliveryType: 1,
            userLatitude: 0,
            userLongitude: 0
        }
    },
    onLoad(options) {
        console.log('自提门店页面参数:', options);
        if (options.items) {
            this.items = JSON.parse(options.items);
        }
        if (options.deliveryType) {
            this.deliveryType = parseInt(options.deliveryType);
        }
        this.getUserLocation();
    },
    onShow() {
        // 监听地址选择事件
        uni.$on('SELECT_ADDRESS', this.handleAddressSelect);
    },
    onHide() {
        // 移除事件监听
        uni.$off('SELECT_ADDRESS', this.handleAddressSelect);
    },
    methods: {
        // 获取用户位置
        getUserLocation() {
            // 先从缓存获取位置信息
            try {
                this.userLatitude = uni.getStorageSync('user_latitude') || 0;
                this.userLongitude = uni.getStorageSync('user_longitude') || 0;
            } catch (e) {
                console.error('获取缓存位置失败:', e);
            }
            
            if (this.userLatitude && this.userLongitude) {
                this.loadStoreList();
            } else {
                this.requestLocation();
            }
        },
        
        // 请求位置权限
        requestLocation() {
            uni.getLocation({
                type: 'gcj02',
                success: (res) => {
                    this.userLatitude = res.latitude;
                    this.userLongitude = res.longitude;
                    // 缓存位置信息
                    try {
                        uni.setStorageSync('user_latitude', res.latitude);
                        uni.setStorageSync('user_longitude', res.longitude);
                    } catch (e) {
                        console.error('缓存位置失败:', e);
                    }
                    this.loadStoreList();
                },
                fail: (err) => {
                    console.error('获取位置失败:', err);
                    uni.showToast({
                        title: '获取位置失败，将显示所有门店',
                        icon: 'none'
                    });
                    this.loadStoreList();
                }
            });
        },
        
        // 加载自提门店列表
        loadStoreList() {
            this.loading = true;
            const params = {};
            if (this.userLatitude && this.userLongitude) {
                params.latitude = this.userLatitude;
                params.longitude = this.userLongitude;
            }
            
            this.$api.req('/trade/delivery/pick-up-store/list', params, 'GET', 'JSON', false).then((res) => {
                this.loading = false;
                if (res.code === 0) {
                    this.storeList = res.data || [];
                    // 计算距离
                    this.calculateDistances();
                } else {
                    uni.showToast({
                        title: res.msg || '加载门店列表失败',
                        icon: 'none'
                    });
                }
            }).catch(() => {
                this.loading = false;
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            });
        },
        
        // 计算距离
        calculateDistances() {
            if (!this.userLatitude || !this.userLongitude) return;
            
            this.storeList.forEach(store => {
                if (store.latitude && store.longitude) {
                    store.distance = this.getDistance(
                        this.userLatitude, 
                        this.userLongitude, 
                        store.latitude, 
                        store.longitude
                    );
                }
            });
            
            // 按距离排序
            this.storeList.sort((a, b) => {
                const distanceA = a.distance || 999999;
                const distanceB = b.distance || 999999;
                return distanceA - distanceB;
            });
        },
        
        // 计算两点间距离（公里）
        getDistance(lat1, lng1, lat2, lng2) {
            const R = 6371; // 地球半径（公里）
            const dLat = this.toRadians(lat2 - lat1);
            const dLng = this.toRadians(lng2 - lng1);
            const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
                Math.sin(dLng / 2) * Math.sin(dLng / 2);
            const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            return R * c;
        },
        
        // 角度转弧度
        toRadians(degrees) {
            return degrees * (Math.PI / 180);
        },
        
        // 选择门店
        selectStore(store) {
            // 通过事件通知父页面
            uni.$emit('SELECT_PICK_UP_INFO', {
                addressInfo: store
            });
            
            // 返回上一页
            uni.navigateBack();
        },
        
        // 拨打电话
        callPhone(phone) {
            if (phone) {
                uni.makePhoneCall({
                    phoneNumber: phone
                });
            }
        },
        
        // 显示地图
        showMap(store) {
            if (store.latitude && store.longitude) {
                uni.openLocation({
                    latitude: Number(store.latitude),
                    longitude: Number(store.longitude),
                    name: store.name,
                    address: `${store.areaName}${store.detailAddress}`
                });
            } else {
                uni.showToast({
                    title: '门店位置信息不完整',
                    icon: 'none'
                });
            }
        }
    }
}
</script>

<style>
.container {
    background: #f5f5f5;
    min-height: 100vh;
}

.header {
    background: #fff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
}

.title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
}

.store-list {
    padding: 20rpx;
}

.store-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
    border-bottom: 1rpx solid #eee;
}

.store-img {
    width: 120rpx;
    height: 120rpx;
    border-radius: 6rpx;
    margin-right: 22rpx;
    flex-shrink: 0;
}

.store-img .img {
    width: 100%;
    height: 100%;
    border-radius: 6rpx;
}

.store-info {
    flex: 1;
    min-width: 0;
}

.store-name {
    font-size: 30rpx;
    font-weight: 800;
    color: #282828;
    margin-bottom: 10rpx;
}

.store-address {
    font-size: 24rpx;
    color: #666666;
    margin-bottom: 8rpx;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.store-phone {
    font-size: 24rpx;
    color: #999;
}

.store-actions {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 15rpx;
    flex-shrink: 0;
    min-width: 120rpx;
}

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
    align-items: center;
}

.phone-btn, .map-btn {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    transition: all 0.3s ease;
    position: relative;
}

.phone-btn:active, .map-btn:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.phone-btn {
    background: linear-gradient(135deg, #e83323 0%, #ff6b6b 100%);
    color: #fff;
}

.phone-btn::after {
    content: '';
    position: absolute;
    top: -2rpx;
    left: -2rpx;
    right: -2rpx;
    bottom: -2rpx;
    background: linear-gradient(135deg, #e83323, #ff6b6b);
    border-radius: 50%;
    z-index: -1;
    opacity: 0.3;
    filter: blur(4rpx);
}

.map-btn {
    background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
    color: #fff;
}

.map-btn::after {
    content: '';
    position: absolute;
    top: -2rpx;
    left: -2rpx;
    right: -2rpx;
    bottom: -2rpx;
    background: linear-gradient(135deg, #4CAF50, #66BB6A);
    border-radius: 50%;
    z-index: -1;
    opacity: 0.3;
    filter: blur(4rpx);
}

.icon-phone, .icon-map {
    font-size: 24rpx;
    line-height: 1;
}

.distance-info {
    text-align: center;
    padding: 8rpx 12rpx;
    background: rgba(232, 51, 35, 0.1);
    border-radius: 20rpx;
    border: 1rpx solid rgba(232, 51, 35, 0.2);
}

.distance-text {
    font-size: 20rpx;
    color: #e83323;
    font-weight: 500;
    line-height: 1.2;
}

.empty, .loading {
    text-align: center;
    padding: 100rpx 0;
    color: #999;
    font-size: 28rpx;
}
</style>
